/**
 * 中青交互类
 */
/* global global:false */  
const hook2global = global.__proto__ || global
export default class Youth {
  constructor(app) {
    this.$app=app
    this.$def=app.$def
  }
  /**
   * 保存远程图片到本地相册 
   * @param {String} url 图片地址
   * @param {Boolean} isHash  是否重命名为hash模式
   * @param {Boolean} isShowToast 保存成功后是否展示toast
   */
  saveImage(url,isHash=false,isShowToast=true){
    let imageTypeList=['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff']
    if(url.indexOf('?')!=-1){
      url=url.substring(0,url.indexOf('?'))
    }
    console.log('saveImage',url,url.lastIndexOf('.'))
    //获取最后一个.的位置
    var spotIndex= url.lastIndexOf('.')
    let ext=url.substr(spotIndex+1)
    if(imageTypeList.indexOf(ext.toLowerCase()) == -1){
      prompt.showToast({
        message:'请传入图片格式'
      })
      return 
    }
    this.download(url,isHash,(data)=>{
      if(data.code==1){
        this.saveToPhotosAlbum(data.data.uri,'图片',isShowToast)
      } 
    })
  }


  /** 
   * download media 下载文件
   * @param {String} url 下载地址
   * @param {Boolean} isHash  是否启用hash名字
   * @param {Function} callback 回调
  */
  download(url,isHash,callback){
    let agreementList=['http','https']
    let firstIndex=url.indexOf(':')
    let agreement=url.substring(0,firstIndex)
    if(agreementList.indexOf(agreement)==-1){
      this.$def.prompt.showToast({
        message:'请传入http或者https链接'
      })
      return
    }
    let spotIndex= url.lastIndexOf('.')
    let ext=url.substr(spotIndex+1)
    let fileFinalTipLastIndex=url.lastIndexOf('/',spotIndex)
    let fileName=url.substring(fileFinalTipLastIndex+1,spotIndex)+'.'+ext
    let downLoadData={}
    downLoadData.url=url
    if(isHash){
      downLoadData.filename=this.$def.$utils.createHash(10)
    }else{
      downLoadData.filename=fileName
    }
    console.log('fileName',fileName)
    this.$def.request.download({
      ...downLoadData,
      success:data=> {
        this.$def.request.onDownloadComplete({
          token: data.token,
          success: completeData=> {
            console.log(`下载成功${completeData.uri}`)
            if(callback){
              let cbData={
                code:1,
                data:completeData
              }
              callback(cbData)
            }
          },
          fail: (data, code)=> {
            console.log(`下载失败, code = ${code}`)
            if(callback){
              let cbData={
                code:code,
                data:data
              }
              callback(cbData)
            }
          }
        })
      },
      fail:(data, code)=> {
        console.log(`下载失败, code = ${code}`)
          
      }
    })
  }
  /** 
   * 保存文件到相册
   * @param {String} uri 文件本地地址
   * @param {String} type toast 提示信息 类型
   * @param {Boolean} isShowToast 是否展示toast提示
   * @param {Function} callback 回调
  */
  saveToPhotosAlbum(uri,type='文件',isShowToast=true,callback){
    console.log('saveToPhotosAlbum:',uri)
    this.$def.media.saveToPhotosAlbum({
      uri: uri,
      success: (data)=>{
        if(isShowToast){
          this.$def.prompt.showToast({
            message:`保存${type}成功`
          })
        }
        if(callback){
          let cbData={
            code:1,
            data:data
          }
          callback(cbData)
        }
      },
      fail:(data, code)=> {
        console.log(`保存图片失败, 错误码：${code}`)
        if(callback){
          let cbData={
            code:code,
            data:data
          }
          callback(cbData)
        }
      }
    })
  }
  /** 
   * 分享微信
  */
  share(data,success){
    let position=0
    if(data.position){
      position=data.position
    }
    if(data.pos){
      position=data.pos
    }
    if(!this.$app.$def.isInstallWeixin){
      this.$app.$def.prompt.showToast({
        message:'请安装微信'
      })
      return
    }
    this.$app.setAppData('shareStart',new Date().getTime())
    this.$app.setAppData('invite_position',position)
    this.$def.serviceShare.share({
      shareType: data.shareType,
      title: data.title,
      imagePath: data.imagePath,
      targetUrl: data.targetUrl,
      summary: data.summary ? data.summary : '中青看点',
      platforms: [data.platforms], 
      success: (cbData) => {
        success&&success(cbData)
        if(data.upload){
          this.$app.setAppData('isUpload',true)
        }
        this.$app.setAppData('isShareSuccess',true)
        this.$app.$def.pubsubModel.publish('shareSuccess')
      },
      fail: (data) => {
        this.$def.serviceShare.share({
          shareType: data.shareType,
          title: data.title,
          imagePath: data.imagePath,
          targetUrl: data.targetUrl,
          summary: data.summary ? data.summary : '中青看点',
          success: ()=> {
            if(success){
              success()
            }
          }
        })
      }
    })
  }
  /**
   * 
   * @param {*} pkg  包名  example:cn.youth.news
   * @param {*} url  跳转打开app协议地址 youthkd://splash
   */
  installApp(pkg,url,callback){
    this.hasInstalledApp(pkg,(bol)=>{
      if(bol){
        this.$def.router.push({
          uri:url
        })
        let sendData={
          code:2
        }
        callback&&callback(sendData)
      }else{
        this.$def.pkg.install({
          package: pkg,
          success:data=> {
            let sendData={
              code:1,
              data
            }
            callback&&callback(sendData)
          },
          fail:(data, code)=> {
            let sendData={
              code:code,
              data
            }
            callback&&callback(sendData)
          }
        })
      }
    })
  }
  /**
   * 监测是否安装
   * @param {String} pkg 包名
   * @param {Function} callback 回调  bol 
   */
  hasInstalledApp(pkg,callback){
    this.$def.pkg.hasInstalled({
      package: pkg,
      success:data=> {
        if(callback){
          callback(data.result)
        }
      },
      fail:()=> {
        callback(false)
      }
    })
  }
  /**
  * 通过功能名字生成日期key 唯一
  * @param {*} name 
  */
  getDateDataByName(name){
    let currentKey=this.$def.$utils.getCurrentDateKey()
    let yesterDayKey=this.$def.$utils.getCurrentDateKey()-1
    let currentNameKey =currentKey+'_'+hook2global.$commonData.uid+'_'+name
    let yesterDayNameKey=yesterDayKey+'_'+hook2global.$commonData.uid+'_'+name
    return {currentNameKey,yesterDayNameKey}
  }
 
}
